package person.lance.socketdemo;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TcpClent {

    Socket socket;
    InputStream in;
    BufferedReader read;

    public void init() throws IOException {
        socket = new Socket("127.0.0.1", 9999);
        in = socket.getInputStream();
        read = new BufferedReader(new InputStreamReader(in));
    }

    public void run() throws IOException {
        init();
        OutputStream out = socket.getOutputStream();
        out.write("adsad".getBytes());
        out.flush();
        while (true){}
//        new Thread(new Read(read)).start();
//        new Thread(new Write(socket)).start();

    }

    public static void main(String[] args) throws IOException {
//        TcpClent tcpClent = new TcpClent();
//        tcpClent.run();
        Socket socket = new Socket("localhost", 9999);
//        InputStream in = socket.getInputStream();

//        根据输入输出流和服务端连接
        OutputStream outputStream=socket.getOutputStream();//获取一个输出流，向服务端发送信息
        PrintWriter printWriter=new PrintWriter(outputStream);//将输出流包装成打印流
        printWriter.print("服务端你好，我是Balla_兔子");
        printWriter.flush();
        socket.shutdownOutput();//关闭输出流


        OutputStream out = socket.getOutputStream();
        out.write("asdsadsadsds\n".getBytes());
        out.flush();
        out.flush();
//        socket.close();
        out.close();
    }

    class Read implements Runnable {
        BufferedReader read;

        Read(BufferedReader read){
            this.read = read;
        }

        public void run() {
            System.out.println("readthread runing");
            while (true) {
                String line = null;
                try {
                    line = read.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println(line);
            }
        }
    }

    class Write implements Runnable {

        Socket socket;

        Write(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            Scanner scanner;
            OutputStream out;
            scanner = new Scanner(System.in);
            System.out.println("write running");
            try {
                out = socket.getOutputStream();
                out.write("abc".getBytes());
                while (true) {
                    String str = scanner.nextLine();
                    System.out.println("输入" + str);
                    out.write(str.getBytes());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

